// Piirtoon liittyviä asioita

public class Table {
  
  Game game;
  HashMap<Block, Integer> bcolors;
  
  Table(Game game) {
    this.game = game;
    this.bcolors = new HashMap<Block, Integer>();
    
    // testing stuff
    /*
    BlockFactory bf = new BlockFactory();
    Block b = bf.createBlock(0);
    b.add(width/4*3-10, height/2);
    b.add(width/4*3+60, height/2);
    b.add(width/4*3-8, height/2+70);
    b.add(width/4*3+64, height/2+72);
    game.completedBlocks.add(b);
    */
  }
  
  void draw() {
    ArrayList<Block> incompleteblocks = game.getIncompleteBlocks();
    
    // No man's land
    int noMansLeft = 
      game.noMansLandPosition - game.noMansLandSize/2;
    int noMansRight = 
      game.noMansLandPosition + game.noMansLandSize/2;
    int rightWidth = width - noMansRight - margin;
    fill(200);
    noStroke();
    rect(noMansLeft, margin, game.noMansLandSize, height-margin*2);
    
    // Play area
    noFill();
    stroke(200);
    strokeWeight(2);
    rect(margin, margin, width-margin*2, height-margin*2);
    stroke(230+phase,155+phase*3,55+phase*5);
    strokeWeight(6);
    line(margin, margin, margin, height-margin*2);
    line(width-margin, margin, width-margin, height-margin*2);
    
    // Blocks
    displayTemplates();
    noStroke();
    fill(150, 50);
    for(Block b : incompleteblocks) {
      b.draw();
    }  
    //stroke(255);
    //strokeWeight(1);
    try {
      for(Block b : game.completedBlocks) {
        fill(getFillColor(b));
        if(b.selected == null) b.go();
        b.draw();
      }  
    } catch (ConcurrentModificationException e) {
      e.printStackTrace(); 
    }
   
    // Touch feedback
    ellipseMode(CENTER);
    noStroke();
    fill(150, 40);
    for(Object o : tuioClient.getTuioCursors()) {
      TuioCursor c = (TuioCursor) o;
      ellipse(c.getScreenX(width), c.getScreenY(height), 15, 15);
      ellipse(c.getScreenX(width), c.getScreenY(height), 18, 18);
      ellipse(c.getScreenX(width), c.getScreenY(height), 21, 21);
    }
  }
  
  void displayTemplates() {
    int xpos = game.noMansLandPosition;
    int n = game.blockTemplates.size();
    int ymargin = 3*margin;
    int gap = 0;
    int ypos = ymargin;
    
    if(n > 1) {
      gap = (width-2*ymargin)/(n-1);
    } else {
      ypos = height/2;
    }
    strokeWeight(2);
    stroke(220);

    for(Block b : game.blockTemplates) {
      if(b.newCounter > 0) {
        b.newCounter--;
        fill(160 + phase*5, 160, 160);
      } else {
        fill(160);
      }
      
      b.draw();
      ypos += gap;
    }
  }
  
  color getFillColor(Block b) {
    if(bcolors.get(b) == null) {
      bcolors.put(b, (int) parseInt(random(255)));
    }

    int r = bcolors.get(b);
    return color(r, 255-r, r*1.5);
  }
  
}
